﻿using Magicodes.ExporterAndImporter.Excel;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.PKPT;
using NP.BPMReportPlatform.MaterialMasterData.Dto;
using NP.BPMReportPlatform.Utils;
using NP.Enterprise.Utils.Http;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.MaterialMasterData
{
    public class PKPlatformService: BPMReportPlatformAppService, IPKPlatformService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform, _dbProcess;
        private readonly SqlSugarClient _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly IExcelImporter _importer;
        private readonly IMMDOrderService _mmdOrderService;
        private readonly ILogger _logger;
        public PKPlatformService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp,
            IBPMPlatformAppService iBPMPlatformApp, INPRestHttpHelper nPRestHttp, IConfiguration configuration,
            IExcelImporter importer, IMMDOrderService mmdOrderService, ILogger logger)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
            _nPRestHttp = nPRestHttp;
            _importer = importer;
            _mmdOrderService = mmdOrderService;
            _logger = logger;
        }

        /// <summary>
        /// 全景图月度预估导出Excel
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IWorkbook> ExportMonthPanoramExcel(PKMonthPanoramaInput input)
        {
            var dataList = await _mmdOrderService.GetMonthPanorama(input);

            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet("Sheet1");
            sheet.DisplayGridlines = true;
            IRow row = sheet.CreateRow(0); // 添加表头
            IFont font1 = workbook.CreateFont();
            font1.Boldweight = (short)FontBoldWeight.Bold;
            ICellStyle style1 = workbook.CreateCellStyle();
            style1.SetFont(font1);
            style1.VerticalAlignment = VerticalAlignment.Center;
            style1.Alignment = HorizontalAlignment.Center;
            style1.BorderBottom = BorderStyle.Thin;
            style1.BorderLeft = BorderStyle.Thin;
            style1.BorderRight = BorderStyle.Thin;
            style1.BorderTop = BorderStyle.Thin;

            return workbook;
        }

        /// <summary>
        /// 删除记录，某个学校，某个月的所有版本历史数据
        /// </summary>
        public void DeleteRecord(DeleteRecordInput input)
        {
            if (input.id == Guid.Empty)
            {
                throw new Exception("id not found");
            }

            var header = _db.Queryable<PKSubmittedByPrincipal>().First(x => x.Id == input.id);
            if (header == null)
            {
                throw new Exception("数据未找到");
            }

            if (_db.Queryable<PKSubmittedByPrincipalReal>().Any(x => x.SchoolName == header.SchoolName
                && x.Year == header.Year && x.Month == header.Month))
            {
                throw new Exception("已有实际排课，无法作废");
            }

            var details = _db.Queryable<PKSubmittedByPrincipalDetail>().Where(x => x.InstanceNumber == header.InstanceNumber).ToList();
            var histories = _db.Queryable<PKSubmittedByPrincipalHistory>()
                .Where(x => x.SchoolName == header.SchoolName && x.Year == header.Year && x.Month == header.Month).ToList();

            var delHeader = ObjectMapper.Map<PKSubmittedByPrincipal, PKSubmittedByPrincipal_DeleteRecord>(header);
            var delDetails = ObjectMapper.Map<List<PKSubmittedByPrincipalDetail>, List<PKSubmittedByPrincipalDetail_DeleteRecord>>(details);
            var delHistories = ObjectMapper.Map<List<PKSubmittedByPrincipalHistory>, List<PKSubmittedByPrincipalHistory_DeleteRecord>>(histories);

            delHeader.DeleteTime = DateTime.Now;
            delHeader.DeleteUser = CurrentUser.UserName;
            delDetails.ForEach(x =>
            {
                x.DeleteUser = CurrentUser.UserName;
                x.DeleteTime = DateTime.Now;
            });
            delHistories.ForEach(x =>
            {
                x.DeleteUser = CurrentUser.UserName;
                x.DeleteTime = DateTime.Now;
            });

            try
            {
                _db.BeginTran();

                _db.Deleteable(header).ExecuteCommand();
                _db.Deleteable(details).ExecuteCommand();
                _db.Deleteable(histories).ExecuteCommand();

                _db.Insertable(delHeader).ExecuteCommand();
                _db.Insertable(delDetails).ExecuteCommand();
                _db.Insertable(delHistories).ExecuteCommand();

                _db.CommitTran();
            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                _logger.Error($"DeleteRecord RollbackTran:{input.id},{ex.Message}");
                throw new Exception(ex.Message);
            }
        }
    }
}
